package com.huidatech.mpgdemo.util;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import org.jsoup.helper.StringUtil;

import java.io.IOException;
import java.util.Map;

/**
 * @Description:
 * @Author: Wangzz
 * @Version: 1.0.0
 * @CreateDate: Created in 2021/11/3 23:19
 * @UpdateDate: [dateFormat:YYYY-MM-DD][modifier][description]
 */
public class HtmlUnitUtils {
    public static void main(String[] args) throws Exception {
        HtmlUnitBuilder builder = HtmlUnitBuilder.config()
                .url("http://www.baidu.com")
                .enableJS(true)
                .enableCookie(true);
        getPage(builder).asText();
    }

    public void test(){


    }

    public static HtmlPage getPage(HtmlUnitBuilder builder)throws Exception{
        WebClient webClient = getWebClient(builder);
        int count = -1;
        while(true){
            try {
                count++;
                return webClient.getPage(builder.url());
            }
            catch (Exception e){
                if(e instanceof IOException && count < builder.retry()){
                    //日志打印：e,重试次数:i,再次执行
                }else {//如果url错误等情况
                    //执行失败，抛出异常
                    throw e;
                }
            }
        }
    }

    public static WebClient getWebClient(HtmlUnitBuilder builder){
        WebClient webClient = null;
        if(isBlank(builder.proxyHost())){
            webClient = new WebClient(BrowserVersion.CHROME);
        }else{
            webClient = new WebClient(BrowserVersion.CHROME,builder.proxyHost(),builder.proxyPort());
            if(!isBlank(builder.username())){ //需要验证的代理服务器
                ((DefaultCredentialsProvider) webClient.getCredentialsProvider()).
                        addCredentials(builder.username(),builder.password());
            }
        }
        //浏览器基本设置
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常
        webClient.getOptions().setCssEnabled(builder.enableCSS());//是否启用CSS
        webClient.getOptions().setJavaScriptEnabled(builder.enableJS()); //默认设置为禁用
        if(builder.enableAjax()) {
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX
        }

        if(builder.enableCookie()){
            webClient.getCookieManager().setCookiesEnabled(true);
            for(Map.Entry<String,String> pair:builder.cookies().entrySet()){
                webClient.getCookieManager().addCookie(new Cookie("/",pair.getKey(),pair.getKey()));
            }

        }
        webClient.waitForBackgroundJavaScript(builder.waitForBackgroundJavaScript());
        Map<String,String> headers = builder.headers();
        if(headers!=null&&headers.size()>0){
            for(Map.Entry<String,String> header:headers.entrySet()){
                webClient.addRequestHeader(header.getKey(),header.getValue());
            }
        }
        return webClient;
    }

    /**
     * org.jsoup.helper.StringUtil
     * @param string
     * @return
     */
    private static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    }
    private static boolean isWhitespace(int c){
        return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r';
    }
}